﻿; (function () {

    'use strict';


    window.GridHelper = window.GridHelper || {};

    GridHelper.getCellsOfCandidate = function (grid, value) {
        var cells = [];
        for (var i = 0; i < 9; i++) {
            for (var j = 0; j < 9; j++) {
                var cell = grid.cells[i][j];
                if (cell.candidates.has[value])
                    cells.push(cell);
            }
        }
        return cells;
    }

    GridHelper.getCellsOfValue = function (grid, value) {
        var cells = [];
        for (var i = 0; i < 9; i++) {
            for (var j = 0; j < 9; j++) {
                if (grid.cells[i][j].value === value)
                    cells.push(grid.cells[i][j]);
            }
        }
        return cells;
    }

    GridHelper.getFilledCells = function (grid) {
        var cells = [];
        for (var i = 0; i < 9; i++) {
            for (var j = 0; j < 9; j++) {
                var cell = grid.cells[i][j];
                if (!cell.isBase && cell.value > 0)
                    cells.push(cell);
            }
        }
        return cells;
    }

    GridHelper.getErrorsCells = function (grid) {
        var errors = [];
        for (var k = 1; k < 10; k++) {
            for (var i = 0; i < 9; i++) {
                var errorsInLines = GridHelper.getErrorsInGroup(grid.cells[i], k);
                var errorsInColmuns = GridHelper.getErrorsInGroup(grid.cellsByColumn[i], k);
                var errorsInRegions = GridHelper.getErrorsInGroup(grid.cellsByRegion[i], k);
                errors = errors.concat(errorsInLines).concat(errorsInColmuns).concat(errorsInRegions);
            }
        }
        return errors.distinct();
    }

    GridHelper.getErrorsInGroup = function (group, value) {
        var errors = [];
        for (var i = 0; i < 9; i++) {
            if (group[i].value === value)
                errors.push(group[i]);

        }
        if (errors.length > 1)
            return errors;
        return [];
    }

    GridHelper.getMissingCandidatesByCell = function (sourceGrid, modifiedGrid) {
        var candidatesByCell = [];
        for (var i = 0; i < 9; i++) {
            for (var j = 0; j < 9; j++) {
               
                var cell = sourceGrid.cells[i][j];
                var modifiedCell= modifiedGrid.cells[i][j];
                var missingCandidates = [];

                for (var c = 0; c < cell.candidates.count; c++) {
                    var value = cell.candidates.values[c];
                    if (!modifiedCell.candidates.has[value])
                    {
                        missingCandidates.push(value);
                    }
                }

                if (missingCandidates.length > 0)
                    candidatesByCell.push({ cell: cell, missingCandidates: missingCandidates });
            }
        }
        return candidatesByCell;
    }
}(window));
